﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CDStore3Tiers;
using System.Resources;
using System.Reflection;
using System.Globalization;
using System.Configuration;

namespace CuaHangDiaNhac
{
	public partial class frmBackupRestore : DevComponents.DotNetBar.Office2007Form
	{
		log4net.ILog log = log4net.LogManager.GetLogger("Backup-Retore");
		public frmBackupRestore()
		{
			InitializeComponent();
		}


		public string getTenFile(string path)
		{
			string[] array = path.Split('\\');
			string[] array2 = array[array.Count() - 1].Split('.');
			return array2[0];

		}

		public void load()
		{
			tvDanhsach.Nodes.Clear();
			TreeNode node;
			string[] array2 = Directory.GetFiles(System.IO.Directory.GetCurrentDirectory().ToString(), "*.bak");
			foreach (string name in array2)
			{
				node = new TreeNode(getTenFile(name));
				tvDanhsach.Nodes.Add(node);
			}
			docFile();
		}

		private void frmBackupRestore_Activated(object sender, EventArgs e)
		{
			load();
			log.Info(frmLogin.id + ": đã load lên form backup-restore");
		}

		private void btnBackup_Click(object sender, EventArgs e)
		{
			try
			{
				StoreCDDataContext cn = new StoreCDDataContext();
				cn.Connection.ConnectionString = getConfig.getConnection();
				DateTime dt = DateTime.Now;
				string tenFile = dt.Year + "_" + dt.Month + "_" + dt.Day + "_" + dt.Minute + "_" + dt.Second;
				string path = System.IO.Directory.GetCurrentDirectory().ToString() + "\\" + tenFile;
				string qr = "BACKUP DATABASE CuaHangDiaNhac TO  DISK = N'" + path + ".bak' " +
				"WITH NOFORMAT, NOINIT,  " +
				"NAME = N'CuaHangDiaNhac backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";

				cn.ExecuteCommand(qr);
				ghiFile("Backup - Sao lưu dữ liệu !", tenFile + ".bak");
				MessageBox.Show("Sao lưu (backup) dữ liệu thành công !", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
				load();
				log.Info(frmLogin.id + ": đã backup dữ liệu vào file " + tenFile + ".bak");
			}
			catch
			{
				MessageBox.Show("Backup thất bại !", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				log.Error(frmLogin.id + " : backup dữ liệu thất bại");
			}

		}

		private void btnRestore_Click(object sender, EventArgs e)
		{
			try
			{
				StoreCDDataContext cn = new StoreCDDataContext();
				cn.Connection.ConnectionString = getConfig.getConnection();
				string path = System.IO.Directory.GetCurrentDirectory().ToString() + "\\" + tvDanhsach.SelectedNode.Text;
				string qr = "ALTER DATABASE CuaHangDiaNhac " +
							"SET OFFLINE WITH ROLLBACK IMMEDIATE  " +
							"RESTORE DATABASE CuaHangDiaNhac FROM DISK = N'" + path + ".bak' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10 " +

							"ALTER DATABASE CuaHangDiaNhac  " +
							"SET ONLINE WITH ROLLBACK IMMEDIATE  ";

				cn.ExecuteCommand(qr);

				ghiFile("Restore - Phục hồi dữ liệu !", tvDanhsach.SelectedNode.Text + ".bak");

				MessageBox.Show("Phục hồi (restore) dữ liệu thành công !\n\nĐÓNG CÁC TAB HIỆN TẠI HOẶC KHỞI ĐỘNG LẠI CHƯƠNG TRÌNH",
					"Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
				load();
				log.Info(frmLogin.id + ": đã phục hồi dữ liệu từ file " + tvDanhsach.SelectedNode.Text + ".bak");
			}
			catch
			{
				MessageBox.Show("Chưa chọn danh sách hoặc database không tồn tại !", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				log.Error(frmLogin.id + " : phục hồi dữ liệu thất bại");
			}
		}


		public void ghiFile(string loai, string tenfile)
		{
			FileStream file = new FileStream(System.IO.Directory.GetCurrentDirectory().ToString() + "\\logBackup.txt", FileMode.OpenOrCreate, FileAccess.Write);
			StreamWriter wr = new StreamWriter(file);
			wr.BaseStream.Seek(0, SeekOrigin.End);
			wr.WriteLine(loai + "|" + DateTime.Now.ToString() + "|" + tenfile);
			wr.Flush();
			file.Close();
		}

		public void docFile()
		{
			StoreCDDataContext cn = new StoreCDDataContext();
			cn.Connection.ConnectionString = getConfig.getConnection();

			FileStream file = new FileStream(System.IO.Directory.GetCurrentDirectory().ToString() + "\\logBackup.txt", FileMode.Open, FileAccess.Read);
			StreamReader r = new StreamReader(file);

			string chuoi;
			int i = 1;
			List<string[]> list = new List<string[]>();
			while ((chuoi = r.ReadLine()) != null)
			{
				string[] ar = chuoi.Split('|');
				list.Add(new string[] { i.ToString(), ar[0], ar[1], ar[2] });
				i++;
			}
			file.Close();
			DataTable table = ConvertListToDataTable(list);

			dgv.DataSource = table;

		}

		private DataTable ConvertListToDataTable(List<string[]> list)
		{
			DataTable table = new DataTable();

			// Get max columns.
			int columns = 0;
			foreach (var array in list)
			{
				if (array.Length > columns)
				{
					columns = array.Length;
				}
			}

			// Add columns.
			for (int i = 0; i < columns; i++)
			{
				table.Columns.Add();
			}

			// Add rows.
			foreach (var array in list)
			{
				table.Rows.Add(array);
			}

			return table;
		}

		private void frmBackupRestore_Load(object sender, EventArgs e)
		{

		}

		private void lbDpre_Click(object sender, EventArgs e)
		{

		}

		private void lbPre_Click(object sender, EventArgs e)
		{

		}

		private void lbNext_Click(object sender, EventArgs e)
		{

		}

		private void lbDnext_Click(object sender, EventArgs e)
		{

		}

		private void txtPage_KeyDown(object sender, KeyEventArgs e)
		{

		}

		private void txtPage_Leave(object sender, EventArgs e)
		{

		}
	}
}
